package com.im.app.processor;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.im.app.manager.ConversationManager;
import com.im.app.model.*;
import com.im.app.model.User;
import com.im.app.service.*;
import com.im.app.utils.SpringUtils;
import com.im.app.utils.uuid.IdUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.cache.redis.RedisCacheManager;
import org.jim.core.packets.*;
import org.jim.server.JimServerAPI;
import org.jim.server.processor.login.LoginCmdProcessor;
import org.jim.server.protocol.AbstractProtocolCmdProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

import java.util.*;

@Component("loginServiceProcessor")
public class LoginServiceProcessor extends AbstractProtocolCmdProcessor implements LoginCmdProcessor {

    private Logger logger = LoggerFactory.getLogger(LoginServiceProcessor.class);

    private static Map<String,User> cacheUser = new HashMap<>();

    public static LoginServiceProcessor ls;

    @Autowired
    private IUserService userService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IPersonhostService personhostService;

    @Autowired
    private VisitorAvatarService visitorAvatarService;

    @Autowired
    private ConversationsService conversationsService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IGroupMemberService groupMemberService;



    @PostConstruct
    public void init() {
        ls = this;
        ls.userService = this.userService;
        ls.codeService = this.codeService;
        ls.request=this.request;
        ls.personhostService=this.personhostService;
        ls.visitorAvatarService=this.visitorAvatarService;
        ls.conversationsService=this.conversationsService;
        ls.groupService = this.groupService;
        ls.groupMemberService = this.groupMemberService;
    }



    @Override
    public LoginRespBody doLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {

        if(loginReqBody.getType() == 1){
            return doServerLogin(loginReqBody,imChannelContext);
        } else if (loginReqBody.getType() == 2) {
            return doClientLogin(loginReqBody,imChannelContext);
        }
        return LoginRespBody.failed("登录类型有误");
    }


    public LoginRespBody doServerLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext)  {
        String token = loginReqBody.getToken();
        User user = null;
        try {
            user = JedisTemplate.me().get(token, User.class);
            if(user == null){
                return LoginRespBody.failed("获取登录用户失效,请重新登录");
            } else {
                if(new Date().getTime()>user.getEndTime().getTime()) {
                    return LoginRespBody.failed("账号已到期");
                }
                if (user.getStatus()==0){
                    return LoginRespBody.failed("账号已停用");
                }
            }
        } catch (Exception e) {
            return LoginRespBody.failed("未登录");
        }
        LoginRespBody respBody = LoginRespBody.success();

        org.jim.core.packets.User user1 = user.toJIMUser();
        user1.setType(1);
        List<Group> list = getGroups(user);
        user1.setGroups(list);
        respBody.setUser(user1);
        return respBody;
    }

    //用户登录
    public LoginRespBody doClientLogin(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {
        String token = loginReqBody.getToken();
        User user = null;
        try {
            user = JedisTemplate.me().get(token, User.class);
            if(user == null){
                return LoginRespBody.failed("获取登录用户失效,请重新登录");
            }
        } catch (Exception e) {
            return LoginRespBody.failed("获取登录用户失效,请重新登录");
        }

        user.setOnline(true);
        LoginRespBody respBody = LoginRespBody.success();
        org.jim.core.packets.User user1 = user.toJIMUser();
        user1.setType(2);
        user1.setKefuId(user.getKefuId());
        List<Group> list = getGroups(user);
        user1.setGroups(list);
        respBody.setUser(user1);
        return respBody;
    }


    public List<Group> getGroups(User user){
        GroupMember member = new GroupMember();
        member.setUserId(user.getUserId());
        List<Group> list = new ArrayList<>();

        List<GroupMember> groupMembers = ls.groupMemberService.selectGroupMemberList(member);
        if (groupMembers.size() > 0){
            List<String> groupIds = new ArrayList<>();
            for (GroupMember member1 : groupMembers){
                groupIds.add(member1.getGroupId());
            }
            IGroupService groupService = SpringUtils.getBean(IGroupService.class);
            QueryWrapper<Group> groupQueryWrapper = new QueryWrapper<>();
            groupQueryWrapper.in("group_id",groupIds);

            String[] ids = groupIds.toArray(new String[0]);
            list = groupService.selectGroupsByGroupIds(ids);
        }
        return list;
    }


    @Override
    public org.jim.core.packets.User getUser(LoginReqBody loginReqBody, ImChannelContext imChannelContext) {

        return null;
    }

    @Override
    public void onSuccess(org.jim.core.packets.User user, ImChannelContext imChannelContext) {
        ConversationManager.getManager().sendUserOnLine(user.getKefuId(),user.getUserId());
        if(user.getType() == 2){

            ConversationManager.getManager().addCustomerUser(user.getUserId());
        }else if (user.getType() == 1){
            ConversationManager.getManager().addServerUser(user.getUserId());
        }else {
            logger.error("用户类型不对{}",user);
        }
    }

    @Override
    public void onFailed(ImChannelContext imChannelContext) {

    }
}
